<?php
/**
 * 后台菜单服务层
 * @author maniac
 */
namespace app\common\service;

use app\common\model\AdminMenus AS AdminMenusModel;
use app\common\model\UserRoles;

class AdminMenus extends Base
{
    /**
     * 获取所有后台菜单
     * @param object $where 查询条件
     */
    public function adminMenus($where = '')
    {
        $menus = AdminMenusModel::field('id,parent_id,name,icon,url,status,list_order')->where($where)->order('list_order DESC,id ASC')->select();
        return $menus;
    }
    
    /**
     * 格式化后台菜单
     * @param  int    $role_id 用户角色 id
     * @param  object $where   查询条件
     */
    public function formatMenus($role_id, $where = '')
    {
        $menus = $this->adminMenus($where);
        // 超级管理员直接返回后台所有菜单
        if ($role_id == 1) return $menus;
        
        $auth = UserRoles::field('authorities')->where('id', $role_id)->find();
        foreach ($menus as $key => $menu) {
            if (!trim($menu['url'])) {
                $temp = AdminMenusModel::where([['id', 'in', get_sub_ids('app\common\model\AdminMenus', $menu['id'])], ['url', 'neq', '']])->column('url');
                $menus[$key]['url'] = $temp;
            }
        }

        $data = [];
        foreach ($menus as $k => $v) {
            if ($v['id'] == 15) {
                // 管理信息
                $data[$v['id']] = $v;
            } else {
                if (is_array($v['url']) && !empty($v['url'])) {
                    foreach ($v['url'] as $url) {
                        if (in_array($url, $auth['authorities']) && !isset($data[$v['id']])) {
                            $data[$v['id']] = $v;
                        }
                    }
                } elseif ($v['url'] && in_array($v['url'], $auth['authorities']) && !isset($data[$v['id']])) {
                    $data[$v['id']] = $v;
                }
            }
        }
        return $data;
    }
}
